package dk.itu.iwjx.helper;

import java.sql.*;
import java.util.*;

import dk.itu.iwjx.beans.PizzaBean;


/**
 * Contains methods to Create Read Delete Update Pizza
 * @author li
 *
 */
public class PizzaHelper {
	private PreparedStatement prest;
	private String sql;	
	
	// return an map of pizzabeans
	public Map<Integer,PizzaBean> getAllPizzas() throws SQLException {
		Map<Integer,PizzaBean> pizzaList = new HashMap<Integer,PizzaBean>();
		
		sql="SELECT id, name, price, description,img FROM pizza";
		prest = DBConnection.getConn().prepareStatement(sql);
		ResultSet results = prest.executeQuery();

		// get row data
		while (results.next()) {
			PizzaBean pb = new PizzaBean();
			pb.setId(results.getInt(1));
			pb.setName(results.getString(2));
			pb.setPrice(results.getFloat(3));
			pb.setDescription(results.getString(4));
			pb.setImg(results.getString(5));

			pizzaList.put(pb.getId(),pb);
		}

		return pizzaList;
	}
	
	//add a pizza to the database
	public void addPizza(PizzaBean pb) throws SQLException{
		sql="INSERT INTO pizza( "
			+ "name, price, img,description ) " + "VALUES ( ?, ?, ? ,?)";
		prest=DBConnection.getConn().prepareStatement(sql);
		
		prest.setString(1,pb.getName());
		prest.setFloat(2,pb.getPrice());
		prest.setString(3,pb.getImg());
		prest.setString(4,pb.getDescription());
		
		prest.executeQuery();
	}
	

	//remove a pizza from the database
	public void removePizza(PizzaBean pb) throws SQLException{
		sql=" DELETE FROM pizza WHERE id= ? ";
		prest=DBConnection.getConn().prepareStatement(sql);
		
		//an id would be enough
		prest.setInt(1,pb.getId());
		prest.execute();
	}
	
	// close statements and terminate database connection
	protected void finalize() {
		// attempt to close database connection
		try {
			prest.close();
			DBConnection.close();
		}
		// process SQLException on close operation
		catch (SQLException sqlException) {
			sqlException.printStackTrace();
		}
	}

}
